﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZF.WS.UserControls;
using GCELibrary.Current;
using System.Transactions;
using ZF.BLL;
using Newtonsoft.Json;
using ZF.BLL.Admin;
using ZF.Model;
 
namespace ZF.WS.Admin
{
    public class Merchandise : ZF.BLL.Page.MMPage
    {
        public override ModuleType Module
        {
            get { return ModuleType.S_Shop; }
            protected set
            {
                base.Module = value;
            }
        }
        public virtual string ListPage { get { return string.Format("{0}/shop/Merchandiselist.aspx", AppKey.SiteKey.ManageDirectory); } }
        public virtual string ManagePage { get { return string.Format("{0}/shop/MerchandiseManage.aspx", AppKey.SiteKey.ManageDirectory); } }
        public virtual string CTitle { get { return "商品"; } }
    }
    public partial class MerchandiseManage : Merchandise
    {
    

        [PageArgument(Key = "id", CanNull = false, BindOperType = PageOperType.Edit)]
        public int MerchandiseId { get; set; }
        protected void Page_Load(object sender, EventArgs e)
        {
    
            if (!IsPostBack)
            {
                if (this.OperType == PageOperType.AddNew)
                    Add();
                else if (this.OperType == PageOperType.Edit)
                    Edit();
            }
        }
        public void InitControls()
        {
            var ptlist = DictionaryConfig.MTypeJsonList.Select(p => p.MType)
               .Where(p => p.ParentId == 0).Select(p => new SimpleTree<int>()
               {
                   Id = p.MerchandiseTypeId,
                   Name = p.Name,
                   ParentId = 0,
               }).ToList();

            DictionaryConfig.MTypeJsonList.Select(p => p.MType)
            .ToList().ForEach(p =>
            {
                if (p.ParentId != 0)
                {
                    var parent = ptlist.FirstOrDefault(pt => pt.Id == p.ParentId);
                    if (parent != null)
                    {
                        parent.Childs.Add(new SimpleTree<int>()
                        {
                            Id = p.MerchandiseTypeId,
                            Name = p.Name,
                            ParentId = p.ParentId,
                        });
                    }
                }
            });
            ptlist.ForEach(p =>
                {
                    this.ddlParams.Items.Add(new ListItem(  p.Name,p.Id.ToString()));
                    p.Childs.ForEach(c => this.ddlParams.Items.Add(new ListItem( "└┈┈" + c.Name,c.Id.ToString())));
                });
            using (var dc = SiteInfo.CreateDBDataContext())
            {
                this.ddlFreight.DataSource = dc.SP_Freight.Select(p => new
                {
                    Key=p.FreightId,
                    Text=p.Name,
                }).ToList();
                this.ddlFreight.DataBind();
            }
            //this.lvMTypeParams.DataSource = DictionaryConfig.MTypeJsonList;
            //this.lvMTypeParams.DataBind();
        }

        public void Add()
        {
            InitControls();
            this.fckInfo.Value = SiteInfo.SystemConfig.ShopTemplate;

        }
        public void AddSubmit(object sender, EventArgs e)
        {


            using (var dc = SiteInfo.CreateDBDataContext())
            {

                var cp = this.tbCPrice.Text.Convert<decimal>();
                var integral =  this.tbIntegral.Text.EmptyInt(0);
                var mp = this.tbMPrice.Text.Convert<decimal>(cp); ;
                var merc = new ZF.Model.SP_Merchandise()
                {
                    Name = this.tbName.Text.Trim(),
                    CPrice = cp,
                    MPrice = mp,
                    Integral = integral,
                    Discount = 10,
                    AddTime = DateTime.Now,
                    Hits = 0,
                    Info = this.fckInfo.Value,
                    //EndTime = this.tbEndTime.Text.EmptyDateTime(),
                    FreightSet = GetFreightSet(),
                    IsHot = this.cbIsHot.Checked,
                    IsSell = this.cbIsSell.Checked,
                    IsPromotions = this.cbIsPromotions.Checked,
                    IsRecommend = this.cbIsRecommend.Checked,
                    Param = this.tbParams.Text,
                    Photo = this.SWFUpLoad1.UpLoadFileInfos.ConstituteString(";"),
                    Quantity = this.tbQuantity.Text.Convert<int>(),
                    Tips = this.fckTips.Value,
                    Unit = this.ddlUnit.SelectedValue == "自定义" ? this.tbUnit.Text : this.ddlUnit.SelectedValue,
                    MerchandiseTypeId = this.ddlParams.SelectedValue.Convert<int>(),
                    IsDel = false,
                    FreightId = ddlFreight.SelectedValue == "" ? null : ddlFreight.SelectedValue.Convert<int?>(),

                    Distribution = this.tbDistribution.Text,
                    No = Guid.NewGuid().ToString(),
                    OrderID = this.tbOrderID.Text.EmptyInt(0),
                };


                try
                {
                    dc.SP_Merchandise.InsertOnSubmit(merc);
                    dc.SubmitChanges();
                    if (this.cbAutoNo.Checked)
                        merc.No = (10000 + merc.MerchandiseId).ToString();
                    else
                        merc.No = this.tbNo.Text;
                    dc.SubmitChanges();
                }
                catch (Exception ex)
                {
                    throw WarnFactory.CreateWarn(ex);
                }
                string msgKey = CTitle;

                SiteInfo.InsertLog("添加" + msgKey, null);
                WarnMessageLink link = new WarnMessageLink(string.Format("成功添加一个{0}，点击确定按钮返回上一页", msgKey));
    
                link.AddWarnMessageLink(string.Format("继续添加{0}", msgKey), Request.Url.ToString());

                WarnFactory.CreateWarn(link.ToString(), WarnIcon.Success, ListPage).Alert();

            }

        }

        public void Edit()
        {
            using (var dc = BLL.SiteInfo.CreateDBDataContext())
            {

                var merc = dc.SP_Merchandise.FirstOrDefault(p => p.MerchandiseId == this.MerchandiseId );
                if (merc == null)
                    throw WarnFactory.CreateWarn(WarnCode.ReocrdNoFind);
                InitControls();
                this.tbName.Text = merc.Name;
                this.tbCPrice.Text = merc.CPrice.ToString();
                this.tbIntegral.Text = merc.Integral.ToString();
                this.tbMPrice.Text = merc.MPrice.ToString();
                this.fckInfo.Value = merc.Info;
           
                this.cbIsHot.Checked = merc.IsHot;
                this.cbIsSell.Checked = merc.IsSell;
  
                this.cbIsPromotions.Checked = merc.IsPromotions;
                this.cbIsRecommend.Checked = merc.IsRecommend;
                this.tbParams.Text = merc.Param;
                this.tbPhoto.Text = merc.Photo;
                this.ddlFreight.SelectedValue = merc.FreightId.HasValue ? merc.FreightId.ToString() : "";
                this.lvImgList.DataSource = merc.Photo.EmptyString("").Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(p => new
                    {
                        File = p
                    });
                this.lvImgList.DataBind();
                this.tbQuantity.Text = merc.Quantity.ToString();
                this.fckTips.Value = merc.Tips;
                this.tbOrderID.Text = merc.OrderID.ToString();
                var listitem = this.ddlUnit.Items.FindByValue(merc.Unit);
                if (listitem != null)
                    this.ddlUnit.SelectedValue = listitem.Value;
                else
                {
                    this.ddlUnit.SelectedValue = "自定义";
                    this.tbUnit.Text = merc.Unit;
                }
                this.ddlParams.SelectedValue = merc.MerchandiseTypeId.ToString();
               
                this.tbDistribution.Text = merc.Distribution;

                SetFreightSet(merc.FreightSet);

            }
        }
        public void EditSubmit(object sender, EventArgs e)
        {

            using (var ts = new System.Transactions.TransactionScope())
            {
                using (var dc = BLL.SiteInfo.CreateDBDataContext())
                {
                    var merc = dc.SP_Merchandise.FirstOrDefault(p => p.MerchandiseId == this.MerchandiseId);
                    if (merc == null)
                        throw WarnFactory.CreateWarn(WarnCode.ReocrdNoFind);
                    merc.Name = this.tbName.Text.Trim();
                    merc.CPrice = this.tbCPrice.Text.Convert<decimal>();
                    merc.Integral = this.tbIntegral.Text.EmptyInt(0);
                    merc.MPrice = this.tbMPrice.Text.Convert<decimal>(merc.MPrice);
                    
                    merc.Discount = 10;
                   
          
                    merc.Info = this.fckInfo.Value;
                    //merc.EndTime = this.tbEndTime.Text.EmptyDateTime();
                    
                    merc.IsHot = this.cbIsHot.Checked;
                    merc.IsSell = this.cbIsSell.Checked;
                    merc.FreightSet = GetFreightSet();
                    merc.IsPromotions = this.cbIsPromotions.Checked;
                    merc.IsRecommend = this.cbIsRecommend.Checked;
                    merc.Param = this.tbParams.Text;
                    merc.FreightId = ddlFreight.SelectedValue == "" ? null : ddlFreight.SelectedValue.Convert<int?>();

                    var photoList = this.tbPhoto.Text.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    photoList.AddRange(this.SWFUpLoad1.UpLoadFileInfos);
                    merc.Photo = photoList.ConstituteString(";");



                    merc.Quantity = this.tbQuantity.Text.Convert<int>();
                    merc.Tips = this.fckTips.Value;
                    merc.Unit = this.ddlUnit.SelectedValue == "自定义" ? this.tbUnit.Text : this.ddlUnit.SelectedValue;
                    merc.MerchandiseTypeId = this.ddlParams.SelectedValue.Convert<int>();

                    merc.OrderID = this.tbOrderID.Text.EmptyInt(0);
                    merc.Distribution = this.tbDistribution.Text;
 
                    try
                    {
                        dc.SubmitChanges();
                        ts.Complete();
                    }
                    catch (Exception ex)
                    {
                        throw WarnFactory.CreateWarn(ex);
                    }
                    string msgKey = CTitle;

                    SiteInfo.InsertLog("修改" + msgKey, null);
                    WarnMessageLink link = new WarnMessageLink(string.Format("成功添加一个{0}，点击确定按钮返回{0}列表", msgKey));

                    link.AddWarnMessageLink(string.Format("重新修改{0}", msgKey), Request.Url.ToString());
                    WarnFactory.CreateWarn(link.ToString(), WarnIcon.Success, ListPage).Alert();

                }


            }

        }


        public string GetFreightSet()
        {
            List< FreightSet> list = new List<FreightSet>();
            if (this.cbHY1.Checked)
                list.Add(new FreightSet(1, this.tbHY1.Text.EmptyString("0").Convert<decimal>()));
            if (this.cbHY2.Checked)
                list.Add(new FreightSet(2, this.tbHY2.Text.EmptyString("0").Convert<decimal>()));
            if (this.cbHY3.Checked)
                list.Add(new FreightSet(3, this.tbHY3.Text.EmptyString("0").Convert<decimal>()));
            if (this.cbHY4.Checked)
                list.Add(new FreightSet(4, this.tbHY4.Text.EmptyString("0").Convert<decimal>()));

            return Newtonsoft.Json.JsonConvert.SerializeObject(list);
        }
        public void SetFreightSet(string str)
        {

            List<FreightSet> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<FreightSet>>(str);
            foreach(var item in list)
            {
                switch (item.Type)
                    {
                        case 1:
                            this.tbHY1.Enabled = true;
                            this.cbHY1.Checked = true;
                            this.tbHY1.Text = item.Price.ToString();
                            break;
                        case 2:
                            this.tbHY2.Enabled = true;
                            this.cbHY2.Checked = true;
                            this.tbHY2.Text = item.Price.ToString();
                            break;
                        case 3:
                            this.tbHY3.Enabled = true;
                            this.cbHY3.Checked = true;
                            this.tbHY3.Text = item.Price.ToString();
                            break;
                        case 4:
                            this.tbHY4.Enabled = true;
                            this.cbHY4.Checked = true;
                            this.tbHY4.Text = item.Price.ToString();
                            break;
                    }
            }
           
        }
    }
 
   
}
